/*
 * @Description: 这是登录页
 * @Author: 谢涛
 * @LastEditors: 陈科引
 * @Date: 2019-04-22 19:13:58
 * @LastEditTime: 2021-05-27 11:33:19
 */

import React, { Component } from 'react'
import {  LockOutlined, UserOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import { Form, Input, Button, Select, message } from 'antd';
import { withRouter } from 'react-router-dom'
import { loginApi } from '@/services/basic'
import axios from '../../axios'
import './style.css'
const Option = Select.Option;

class Login extends Component {

    constructor(props) {
        super(props)
        this.state = {
            UserNameFocused: true,//账号框是否获得焦点
            PassWordFocused: false,//密码框是否获得焦点
            InstitutionFocused: false,//医疗机构框是否获得焦点
            PhoneNumberFocused: true,//手机号码框是否获得焦点
            AuthcodeFocused: false,//验证码框是否获得焦点
            username: '',//作为医疗机构是否给与响应的判断依据
            yljg: '',//作为医疗机构是否多选、是否给默认值的依据
            Yljg: [],//医疗机构数据
            userCode: true,//标记是否是用户名/密码方式登录
            time: 60,//倒计时时间
            authCodeSend: false,//标识验证码是否发送
        }
    }

    handleSubmit = (e) => {
        this.form.validateFields().then(values => {
            //后台登录验证
                const method = this.state.userCode ? 'login' : 'phoneLogin'
                loginApi[method]({
                    username: this.state.userCode ? `${values.userName}` : `${values.phoneNumber}`,
                    password: this.state.userCode ? `${values.passWord}` : `${values.authCode}`,
                    yyid: `${values.yyid}`
                })
                    .then((response) => {
                        if (response.code === '1') {
                            sessionStorage.setItem("userInfo", JSON.stringify(response.data));
                            sessionStorage.setItem("isAuthenticated", true);
                            axios.defaults.headers.common['Auth-Token'] = response.data.token;
                            message.success('欢迎登录')
                            this.props.history.replace("/Index/HomePage");
                        } else if (response.code === '-1') {
                            message.warning("用户名不存在");
                        } else {
                            message.error("密码错误");
                        }
                    })
        })
        .catch(error => {
            // eslint-disable-next-line
            console.dir(error)
        });
    }

    checkStatus(status) {
        this.props.checkStatus(status);
    }

    //用户名框获得焦点
    addUserNameStyle = () => {
        this.setState({
            UserNameFocused: true,
            PassWordFocused: false,
            InstitutionFocused: false,
            yljg: ''
        })
    }


    //用户名框失去焦点
    delUserNameStyle = (e) => {
        const { userName, phoneNumber } = this.form.getFieldsValue()
        if (userName || phoneNumber) {
            loginApi.getYljg({ username: userName || phoneNumber })
                .then((res) => {
                    if (res.data && res.data.length !== 0) {
                        const Yljg = res.data.map(item => <Option value={item.yyid} key={item.yyid}>{item.yymc}</Option>)
                        if (res.data.length === 1) {
                            this.setState({
                                yljg: res.data[0].yyid
                            })
                            this.form.setFieldsValue({ yyid: res.data[0].yyid })
                        }
                        this.setState({
                            Yljg: Yljg,
                            UserNameFocused: false,
                        })
                    } else {
                        message.warning(res.msg)
                    }
                })
        }
        // else {
        //     message.warning(`${this.state.userCode ? '请输入用户名' : '请输入手机号'}`)
        // }
    }

    //手机号框获得焦点
    addPhoneNumberStyle = () => {
        this.setState({
            PhoneNumberFocused: true,
            AuthcodeFocused: false,
            InstitutionFocused: false,
            yljg: ''
        })
    }

    //密码框获得焦点
    addPassWordStyle = () => {
        this.delUserNameStyle()
        this.setState({
            PassWordFocused: true,
            UserNameFocused: false,
            InstitutionFocused: false,
        })
    }

    //密码框失去焦点
    delPassWordStyle = () => {
        this.setState({
            PassWordFocused: false,
            UserNameFocused: true,
            InstitutionFocused: false,
        })
    }

    //验证码框获得焦点
    addAuthCodeStyle = () => {
        this.delUserNameStyle()
        this.setState({
            PhoneNumberFocused: false,
            AuthcodeFocused: true,
            InstitutionFocused: false,
        })
    }

    //验证码框失去焦点
    delAuthCodeStyle = () => {
        this.setState({
            PhoneNumberFocused: false,
            AuthcodeFocused: false,
            InstitutionFocused: false,
        })
    }

    //机构框获得焦点
    addInstitutionStyle = () => {
        const { userName } = this.form.getFieldsValue()
        if (!userName) {
            message.warning('请先填写用户名')
        }
        this.setState({
            InstitutionFocused: true,
            UserNameFocused: false,
            PassWordFocused: false,
            PhoneNumberFocused: false,
            AuthcodeFocused: false,
        })
    }

    //机构框失去焦点
    delInstitutionStyle = () => {
        this.setState({
            InstitutionFocused: false,
            UserNameFocused: true,
            PassWordFocused: false,
            PhoneNumberFocused: true,
            AuthcodeFocused: false,
        })
    }

    onSentAuthcode = () => {
        const { phoneNumber } = this.form.getFieldsValue();
        if (phoneNumber === undefined) {
            message.warning('请先填写手机号')
            this.setState({ PhoneNumberFocused: true })
            return false
        }
        loginApi.getCode(phoneNumber)
            .then((res) => {
                if (res.code !== '1') {
                    message.warning('该手机号尚未注册')
                } else {
                    this.setState({ authCodeSend: true })
                    this.onCountDown();
                    message.success('验证码已发送，请注意查收，并及时填写')
                }
            })
    }

    //登录类型切换
    onRegTypeShift = () => {
        this.setState({ userCode: !this.state.userCode })
        this.form.resetFields();
        this.setState({
            yljg: '',
            Yljg: []
        })
    }

    //点击发送验证码后倒计时
    onCountDown = () => {
        let { time } = this.state;
        setInterval(() => {
            if (time > 0) {
                time--
                this.setState({ time }, () => {
                    if (this.state.time <= 0) {
                        this.setState({ time: 60, authCodeSend: false });
                        return false;
                    }
                })
            }
        }, 1000)
    }

    // //用户名回车事件
    onUserNameEnter = () => {
       // this.a.props.onFocus()
        this.a.focus()
    }

    onPassWordEnter = () => {
        //this.b.props.onFocus()
        this.b.focus()
    }

    onUserNameChange = () => {
        // const { userName } = this.form.getFieldsValue()
        this.setState({ Yljg: [], yljg: '' })
        this.form.resetFields(['yyid'])
    }

    render() {
        return (
            <div id="components-form-demo-normal-login">
                <Form autoComplete="off" className="login-form"  ref={form => this.form = form}>

                    <div className='login-header'>
                        <img src={require('./logo.png')}
                         width="120px"
                         height="30px"
                         style={{ margin: '-20px 10px -10px 0px' }}
                         alt=""
                          className='login-header-icon' />
                        <span className='login-header-title' >鹏成车邦</span>
                    </div>

                    <div
                        className={this.state.UserNameFocused ? 'withBac' : 'withoutBac'}
                        style={{ display: this.state.userCode ? 'block' : 'none' }}
                    >
                        <Form.Item
                            name="userName"
                            rules={this.state.userCode ?
                            [
                                { required: true, message: '用户名不能为空!' },
                                { pattern: /^[^ ]+$/, message: '请勿输入空格!' },
                            ] : []}
                        >
                            <Input
                                autoFocus
                                onPressEnter={this.onUserNameEnter}
                                allowClear
                                onFocus={this.addUserNameStyle}
                                onChange={this.onUserNameChange}
                                onBlur={this.delUserNameStyle}
                                autoComplete="username"
                                prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="用户名" />
                        </Form.Item>
                    </div>

                    <div
                        className={this.state.PhoneNumberFocused ? 'withBac' : 'withoutBac'}
                        style={{ display: this.state.userCode ? 'none' : 'block' }}
                    >
                        <Form.Item
                            name="phoneNumber"
                            rules={this.state.userCode ?
                            [] :
                            [
                                { required: true, message: '手机号不能为空!' },
                                { pattern: /^[^ ]+$/, message: '请勿输入空格!' },
                                { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号!' }
                            ]}
                        >
                            <Input
                                allowClear
                                onFocus={this.addPhoneNumberStyle}
                                prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="手机号" />
                        </Form.Item>
                    </div>

                    <div
                        className={this.state.PassWordFocused ? 'withBac' : 'withoutBac'}
                        style={{ display: this.state.userCode ? 'block' : 'none' }}
                    >
                        <Form.Item
                            name="passWord"
                            rules={this.state.userCode ?
                            [{ required: true, message: '密码不能为空!' }] : []}
                        >
                            <Input
                                ref={a => this.a = a}
                                type='password'
                                onFocus={this.addPassWordStyle}
                                onBlur={this.delPassWordStyle}
                                onPressEnter={this.onPassWordEnter}
                                autoComplete="current-password"
                                placeholder="密码"
                                prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
                            />
                        </Form.Item>
                    </div>
                    <div
                        className={this.state.AuthcodeFocused ? 'withBac' : 'withoutBac'}
                        style={{ display: this.state.userCode ? 'none' : 'block' }}
                    >
                        <Form.Item
                            name="authCode"
                            rules={this.state.userCode ?
                            [] : [{ required: true, message: '验证码不能为空!' }]}
                        >
                            <Input
                                allowClear
                                onFocus={this.addAuthCodeStyle}
                                onBlur={this.delAuthCodeStyle}
                                prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="手机验证码"
                                addonAfter={
                                    <Button
                                        disabled={this.state.authCodeSend ? true : false}
                                        className='authCodeButton'
                                        onClick={this.onSentAuthcode}
                                    >{this.state.authCodeSend ? `${this.state.time}s` : '点击发送验证码'}</Button>}
                            />
                        </Form.Item>
                    </div>
                    {/* <p className='getAuthcode'>
                        <span onClick={this.onRegTypeShift}>
                            {this.state.userCode ? '短信验证码登录' : '用户名/密码登录'}
                        </span></p> */}
                    <div className={this.state.InstitutionFocused ? 'withBac' : 'withoutBac'}>
                        <Form.Item
                            name="yyid"
                            rules={[{ required: true, message: '机构不能为空' }]}
                            initialValue={this.state.yljg === '' ? '请选择机构' : this.state.yljg}
                        >
                            <Select
                                ref={b => this.b = b}
                                allowClear
                                notFoundContent={false}
                                showArrow={this.state.yljg === '' ? true : false}
                                onFocus={this.addInstitutionStyle}
                                onBlur={this.delInstitutionStyle}
                                placeholder="请选择机构"
                            >
                                {this.state.Yljg}
                            </Select>
                        </Form.Item>
                    </div>

                    <div style={{ padding: '10px' }}>
                        <Form.Item>
                            <Button type="primary"
                                onClick={this.handleSubmit}
                                className="login-form-button"
                                style={{ margin: '10px 0px' }}
                            >点击登录</Button>
                        </Form.Item>
                    </div>
                    {/* <div style={{ color: 'rgba(255,255,255,.6)', marginTop: '30px' }}>
                        浙江康略软件有限公司 @2010-2019 Tel:0571-8888888
                    </div> */}
                </Form>
            </div>
        );
    }
}

export default withRouter(Login)